package makovo.ajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import makovo.data.Resources;
import makovo.entities.ApplicantWithDocs;

import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONArray;
import org.json.JSONObject;

public class GetApplicantFiles extends HttpServlet implements SessionAware {

	private static final long serialVersionUID = 1L;
	private String mCurp = null;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameterValues("m")[0];
		try {
			if (method.equals("appInfo")) {
				HttpSession session = request.getSession();
				mCurp = (String) session.getAttribute("User.idSender");
				ApplicantWithDocs a = Resources.getApplicantWithDocs(mCurp);

				request.setCharacterEncoding("utf8");
				// response.setCharacterEncoding("utf8");
				response.setContentType("application/json");
				PrintWriter out = response.getWriter();

				JSONObject obj = new JSONObject();
				JSONArray arr = new JSONArray();
				JSONObject item;

				obj.put("name", a.name + " " + a.lastName + " " + a.secondLastName);
				obj.put("address", "Calle: " + a.address.street.toUpperCase() + " Num ext: " + a.address.extNum.toUpperCase()
						+ " Num int: " + a.address.intNum.toUpperCase() + "  Localidad: "
						+ a.address.loc.toUpperCase() + " " + a.address.city.toUpperCase() + ", "
						+ a.address.state.toUpperCase() + " CP  : " + a.address.cp.toUpperCase()
						+ "  Latitud : " + a.address.lat + "  Longitud : " + a.address.lonng);

				obj.put("phone", a.phone);
				obj.put("curp", a.curp);

				for (int i = 0; i < a.getDocs().size(); i++) {
					item = new JSONObject();
					item.put("id_doc_type", a.getDocs().get(i).getTypeDoc().id);
					item.put("path", a.getDocs().get(i).getPath());
					item.put("field", a.getDocs().get(i).getTypeDoc().document);
					item.put("identifier", a.getDocs().get(i).getTypeDoc().identifier);
					arr.put(item);
				}
				obj.put("docs", arr);

				out.print(obj);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void setSession(Map<String, Object> arg0) {
		// TODO Auto-generated method stub
		
	}

}
